#include "common.h"
#include <sstream>  

string SafeGetHostName(const string hostName)
{
	const int HOST_NAME_LENGTH = 255;
	char	szHostName[HOST_NAME_LENGTH] = { 0 };

	if(hostName.empty())
		gethostname(szHostName, HOST_NAME_LENGTH - 1);
	else
		strncpy(szHostName, hostName.c_str(), hostName.size());

	hostent *host_entry;
	host_entry = gethostbyname(szHostName);

	char* localIP = inet_ntoa(*(struct in_addr *)*host_entry->h_addr_list);
	memset(szHostName, 0, HOST_NAME_LENGTH);
	if(localIP != NULL)
		strcpy(szHostName, localIP);

	return szHostName;
}

#ifdef WIN32

void SleepMS(unsigned long msec)
{
	Sleep(msec);
}

void SleepS(unsigned long sec)
{
	Sleep(sec * 1000);
}

uint64 GetCurTime()
{
	return GetTickCount();
}

#elif defined(LINUX)

void SleepMS(unsigned long msec)
{
	usleep(msec * 1000);
}

void SleepS(unsigned long sec)
{
	sleep(sec);
}

uint64 GetCurTime()
{
	struct timeb tp;
	ftime(&tp);
	return tp.time * 1000 + tp.millitm;
}

#endif

char* StringNew(const char* string, const int lenString)
{
	char * data = NULL;

	int lenData = lenString;
	if(lenString == 0 && string != NULL)
		lenData = strlen(string);

	if(lenData != 0 && string != NULL)
	{
		int len = lenData;
		if(lenString == 0)
			++len;
		
		data =  SAFE_NEW char[len];
		memset(data, 0, len);
		memcpy(data, string, lenData);
	}

	return data;
}

char* GetSubstring(const char* src, int pos , char label)
{
	int	lenSrc = strlen(src);
	char* dst = SAFE_NEW char[lenSrc + 1];
	memset(dst, 0, lenSrc + 1);

	int idx = 0;
	int idx0 = 0;
	while(src[idx] != 0)
	{
		if (src[idx] == label)
		{
			idx++;
			pos--;
			continue;
		}

		if (pos == 0)
		{
			dst[idx0] = src[idx];
			dst[idx0+1] = 0;
			idx0++;
		}
		else if (pos < 0)
		{
			break;
		}
		idx++;
	}

	return dst;
}

void SplitString(const string& s, const string& delim, vector<string>& ret)
{
	string::size_type pos_start = 0;
	string::size_type pos_end = 0;

	while(pos_end != string::npos)
	{
		pos_end = s.find_first_of(delim, pos_start);

		if(pos_end != string::npos)
		{
			ret.push_back(s.substr(pos_start, pos_end - pos_start));
			++pos_end;
		}
		else
		{
			ret.push_back(s.substr(pos_start, pos_end));
		}

		pos_start = pos_end;
	}
}

int ParseInt(const string& str)
{
	try
	{
		int value;

		std::stringstream ss(str);

		ss >> value;

		return value;
	}
	catch(...)
	{
		return -1;
	}
}

float ParseFloat(const string& str)
{
	float value;

	std::stringstream ss(str);

	ss >> value;

	return value;
}

string ToString(int num)
{
	std::stringstream ss;

	ss << num;

	return ss.str();	
}